﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CaseManagerLibrary.Models;

namespace CaseManagerLibrary.Auth
{
    public delegate void LoginSuccessEventHandler(ac_user user, object data);
    public delegate void LoginFailEventHAndler(string msg);

    public partial class UserLogin : UserControl
    {
        public event LoginSuccessEventHandler LoginSuccess;
        public event LoginFailEventHAndler LoginFail;
        public string ApiAddress { get; set; }
        private object LoginData;
        public UserLogin()
        {
            InitializeComponent();
        }

        public void SetTitle(Image img)
        {
            picTitle.Image = img;
        }

        public void Show(object data)
        {
            this.Visible = true;
            this.BringToFront();

            LoginData = data;
        }

        public void Logout()
        {
            this.txtUserName.Clear();
            this.txtPassword.Clear();
            LoginService.Logout();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            var result = LoginService.Login(ApiAddress, this.txtUserName.Text.Trim(), this.txtPassword.Text.Trim());

            if (result.success)
            {
                LoginSuccess?.Invoke(LoginService.User, LoginData);
            }
            else
            {
                LoginFail?.Invoke(result.message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.FindForm().Close();
        }

        private void txtUserName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnLogin.PerformClick();
            }
        }

        private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnLogin.PerformClick();
            }
        }
    }
}
